#ifndef _DLIST_H_
#define _DLIST_H_

#include "basetype.h"

template<typename T>
class DList
{
public:
    struct DListNode 
    {
        T   data;
        DListNode*  pPrior;
        DListNode*  pNext;

        DListNode()
        {
            memset(&data, 0, sizeof(data));
            pPrior = NULL;
            pNext = NULL;
        }
    };

public:
    DList(int ASize = 0)
    {
        init(ASize);
    }
    
    void    init(int ASize)
    {
        m_nodePool.init(ASize);
        m_head.pNext = &m_tail;
        m_tail.pPrior = &m_head;
    }

    DListNode*  begin()
    {
        return m_head.pNext;
    }
    
    const DListNode*  end()
    {
        return  &m_tail;
    }

    void    push_back(T AT)
    {
        DListNode* pNewNode = m_nodePool.popPtrElement();
        if(NULL != pNewNode)
        {
            pNewNode->data = AT;

            DListNode* currentTail = m_tail.pPrior;

            currentTail->pNext = pNewNode;
            pNewNode->pPrior = currentTail;

            pNewNode->pNext = &m_tail;
            m_tail.pPrior = pNewNode;
        }
    }

    DListNode*    erase(DListNode* pNode)
    {
        DListNode* pPrior = pNode->pPrior;
        DListNode* pNext = pNode->pNext;

        pPrior->pNext = pNext;
        pNext->pPrior = pPrior;
        
        m_nodePool.pushPtrElement(pNode);

        return pNext;
    }

private:
    DListNode   m_head;
    DListNode   m_tail;

    TypesLib::TypePool<DListNode, true>   m_nodePool;
};

#endif